<?php
declare (strict_types=1);

namespace app\middleware;

use app\message;
use app\service\Token;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;

class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return \app\middleware\Response|false|string
     * @throws \think\Exception
     */
    public function handle(\think\Request $request, \Closure $next)
    {
        #获取header中的token
        $token = $request->header('token');
        if (!$token) {
            $token = $request->get('token');
        }
        if (!$token) {
            echo ReJson(message::$LOGIN_FAILURE, message::$TOKEN_FAILURE);
            exit;
        }

        //判断token 是否多次请求
        // 连接redis
        $redis = Cache::store('redis');
        //判断是否属于add方法
        if (strrpos ($request->pathinfo (), 'add') === 0){

            $str = $request->pathinfo ().$token;  //路由地址拼接token
            if ($redis->get ($str)){
                echo ReJson(message::$ERROR_CODE, message::$TOKEN_RE_FAILURE);
                exit;
            }
            $redis->remember ($str,$str,8);
        }


        if ($token != '99999999999999999999999'){
            $login_token_info = Db::table('login_token')->where('token', $token)->find();
            if (!$login_token_info) {
                echo ReJson(message::$LOGIN_FAILURE, message::$TOKEN_FAILURE);
                exit;
            }
            $user_login_id = $login_token_info['uid'];
            //添加uid参数

            $str = "file/";

            if ($request->isPost()) {
                $param = $request->post();
                $param['user_login_id'] = $user_login_id;
                $request->withPost($param);

            } elseif ($request->isGet()) {
                $param = $request->get();
                $param['user_login_id'] = $user_login_id;
                $request->withGet($param);
            }
        }


        return $next($request);
    }
}
